package com.ruoyi.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.domain.DeployRequest;
import com.ruoyi.domain.ProcessDefinitionDTO;
import com.ruoyi.domain.ProcessInstanceInfo;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.repository.Deployment;
import org.camunda.bpm.engine.repository.ProcessDefinition;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/process")
public class BpmProcessController {
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;

    // 部署流程（接收前端 XML）
    @PreAuthorize("@ss.hasPermi('engine:definition:add')")
    @PostMapping("/deploy")
    public AjaxResult deployProcess(@RequestBody DeployRequest deployRequest) {
        try {
            System.out.println(deployRequest.toString());
            Deployment deployment = repositoryService.createDeployment()
                    .name(deployRequest.getProcessKey() + "-deployment")
                    .addString(deployRequest.getProcessKey() + ".bpmn", deployRequest.getBpmnXml())
                    .deploy();

            String deploymentId = deployment.getId();
            return AjaxResult.success(deploymentId);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    // 查询所有已部署的流程定义（带分页）
    @GetMapping("/list")
    public List<ProcessDefinitionDTO> getDeployedProcessDefinitions() {
        return repositoryService.createProcessDefinitionQuery()
                .orderByProcessDefinitionVersion() // 按版本倒序
                .latestVersion()
                .desc()
                .list()
                .stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }


    private ProcessDefinitionDTO convertToDTO(ProcessDefinition definition) {
        return new ProcessDefinitionDTO(
                definition.getId(),
                definition.getKey(),
                definition.getName(),
                definition.getVersion(),
                definition.getDeploymentId()
        );
    }




    //这个是获取这个流程有没有人在运行  如请假等 而上面那个则是获取部署的已经
    @GetMapping("/instance/running")
    public List<ProcessInstanceInfo> getRunningProcessInstances() {
        return runtimeService.createProcessInstanceQuery()
                .active()
                .list()
                .stream()
                .map(this::convertToInfo)
                .collect(Collectors.toList());
    }

    private ProcessInstanceInfo convertToInfo(ProcessInstance instance) {
        return new ProcessInstanceInfo(
                instance.getId(),
                instance.getProcessDefinitionId(),
                instance.getBusinessKey(),
                instance.isEnded(),
                instance.isSuspended()
                // 添加其他需要的字段
        );
    }
        @DeleteMapping("/{instanceId}")
    public void deleteProcessInstance(@PathVariable String instanceId) {
        try {
            // 第一个参数：实例 ID；第二个参数：删除原因（可选，用于日志记录）
            runtimeService.deleteProcessInstance(instanceId, "手动删除实例");
        } catch (ProcessEngineException e) {
            if (e.getMessage().contains("no process instance found with id")) {
                throw new RuntimeException("实例不存在", e);
            }
            throw e; // 其他异常抛给全局异常处理器
        }
    }
}
